﻿using System.Data.Common;

namespace Vbyte.SharpOrm
{
    public static partial class OrmHelper
    {
        #region Delete
        /// <summary>
        /// 删除满足实例的所有记录
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <returns>返回受影响的记录条数</returns>
        public static int Delete(this TableEntry SqlTableEntry)
        {
            return Delete(SqlTableEntry, null, new string[0], null);
        }

        /// <summary>
        /// 使用已打开的共享连接，删除满足实例的所有记录
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <param name="SharedOpenConnection">已打开的共享数据库连接，只使用不关闭及销毁。</param>
        /// <returns>返回受影响的记录条数</returns>
        public static int Delete(this TableEntry SqlTableEntry, DbConnection SharedOpenConnection)
        {
            return Delete(SqlTableEntry, SharedOpenConnection, new string[0], null);
        }

        /// <summary>
        /// 使用已打开的共享连接，删除满足实例的所有记录
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <param name="SharedOpenConnection">已打开的共享数据库连接，只使用不关闭及销毁。</param>
        /// <param name="NotIgnoreDefaultValueProperties">强制不忽略默认值的字段集合</param>
        /// <returns>返回受影响的记录条数</returns>
        public static int Delete(this TableEntry SqlTableEntry, DbConnection SharedOpenConnection, string[] NotIgnoreDefaultValueProperties)
        {
            return Delete(SqlTableEntry, SharedOpenConnection, NotIgnoreDefaultValueProperties, null);
        }

        /// <summary>
        /// (事务支持)使用已打开的共享连接，删除满足实例的所有记录
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <param name="SharedOpenConnection">已打开的共享数据库连接，只使用不关闭及销毁。</param>
        /// <param name="NotIgnoreDefaultValueProperties">强制不忽略默认值的字段集合</param>
        /// <param name="trans">当前关联的数据库事务</param>
        /// <returns>返回受影响的记录条数</returns>
        public static int Delete(this TableEntry SqlTableEntry, DbConnection SharedOpenConnection, string[] NotIgnoreDefaultValueProperties, DbTransaction trans)
        {
            int result = 0;
            DbCommand cmd = GeneratorDbCommand(SqlTableEntry, SQLRowCommandType.Delete, NotIgnoreDefaultValueProperties);
            if (trans != null) cmd.Transaction = trans;
            if (SharedOpenConnection != null)
            {
                cmd.Connection = SharedOpenConnection;
                result = cmd.ExecuteNonQuery();
            }
            else
            {
                DbConnection conn = new AdoNetAdapter(SqlTableEntry).GetDbConnection();
                conn.Open();

                cmd.Connection = conn;
                //Debug.WriteLine("Delete: " + cmd.CommandText);
                result = cmd.ExecuteNonQuery();

                conn.Close();
                conn.Dispose();
            }
            cmd.Dispose();
            return result;
        }

        #endregion
	}
}
